package com.uzai.console.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.MessageFuncEnum;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.user.UserQuery;
import com.uzai.console.dto.user.app.AppUserQuery;
import com.uzai.console.dto.user.wechatuser.WechatUserQuery;
import com.uzai.console.dto.user.wxpubuser.WxpubUserQuery;
import com.uzai.console.dto.user.wxworkuser.WxworkUserQuery;
import com.uzai.console.entity.AppUser;
import com.uzai.console.entity.Device;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.*;
import com.uzai.console.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private WxworkUserService wxworkUserService;
    @Autowired
    private WxpubUserService wxpubUserService;
    @Autowired
    private AppUserService appUserService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    /***
     * 查询用户列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param userQuery
     * @return null
     */
    public Page<UserInfoVo> findUserPage(UserQuery userQuery) {
        //返回到页面分页对象
        Page<UserInfoVo> pageVo = new Page<>();
        //新建返回到页面的LIST对象
        List<UserInfoVo> userInfoVoList = new ArrayList<>();
        if (StringUtils.isNotBlank(userQuery.getDeviceType())) {
            //个人微信用户
            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(userQuery.getDeviceType())) {
                WechatUserQuery wechatUserQuery = new WechatUserQuery();
                BeanUtils.copyProperties(userQuery, wechatUserQuery);
                //执行分页查询对象
                Page<WechatUser> page = new Page<>();
                wechatUserQuery.convert(page);
                List<WechatUser> wechatUserList = wechatUserMapper.findByList(page, wechatUserQuery);
                BeanUtils.copyProperties(page, pageVo);
                if (wechatUserList != null && wechatUserList.size() > 0) {
                    for (WechatUser wechatUser : wechatUserList) {
                        UserInfoVo userInfoVo = new UserInfoVo();
                        BeanUtils.copyProperties(wechatUser, userInfoVo);
                        userInfoVoList.add(userInfoVo);
                    }
                }
            } else if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(userQuery.getDeviceType())) { //企业微信号
                WxworkUserQuery wxworkUserQuery = new WxworkUserQuery();
                BeanUtils.copyProperties(userQuery, wxworkUserQuery);
                //执行分页查询对象
                Page<WxworkUser> page = new Page<>();
                wxworkUserQuery.convert(page);
                List<WxworkUser> wxworkUserList = wxworkUserMapper.findByList(page, wxworkUserQuery);
                BeanUtils.copyProperties(page, pageVo);
                if (wxworkUserList != null && wxworkUserList.size() > 0) {
                    for (WxworkUser wxworkUser : wxworkUserList) {
                        UserInfoVo userInfoVo = new UserInfoVo();
                        BeanUtils.copyProperties(wxworkUser, userInfoVo);
                        userInfoVoList.add(userInfoVo);
                    }
                }
            } else if (DeviceTypeEnum.WX_PUB.getKey().equals(userQuery.getDeviceType())) { //公众号
                WxpubUserQuery wxpubUserQuery = new WxpubUserQuery();
                BeanUtils.copyProperties(userQuery, wxpubUserQuery);
                //执行分页查询对象
                Page<WxpubUser> page = new Page<>();
                wxpubUserQuery.convert(page);
                List<WxpubUser> wxpubUserList = wxpubUserMapper.findByList(page, wxpubUserQuery);
                BeanUtils.copyProperties(page, pageVo);
                if (wxpubUserList != null && wxpubUserList.size() > 0) {
                    for (WxpubUser wxpubUser : wxpubUserList) {
                        UserInfoVo userInfoVo = new UserInfoVo();
                        BeanUtils.copyProperties(wxpubUser, userInfoVo);
                        userInfoVoList.add(userInfoVo);
                    }
                }
            } else if (DeviceTypeEnum.APP.getKey().equals(userQuery.getDeviceType())) { //APP会员
                AppUserQuery appUserQuery = new AppUserQuery();
                BeanUtils.copyProperties(userQuery, appUserQuery);
                //执行分页查询对象
                Page<AppUser> page = new Page<>();
                appUserQuery.convert(page);
                List<AppUser> appUserList = appUserMapper.findByList(page, appUserQuery);
                BeanUtils.copyProperties(page, pageVo);
                if (appUserList != null && appUserList.size() > 0) {
                    for (AppUser appUser : appUserList) {
                        UserInfoVo userInfoVo = new UserInfoVo();
                        BeanUtils.copyProperties(appUser, userInfoVo);
                        userInfoVoList.add(userInfoVo);
                    }
                }
            }
        }
        pageVo.setRecords(userInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }


    /**
     * 根据设备类型查询用户信息
     *
     * @param userId
     * @param deviceType(有设备类型，咋根据设备类型匹配会员类型查询;//如果没有设备类型，则依次去各种会员类型表中查询，查询到就返回)
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public User findUserInfo(Long userId, String deviceType, Long merId) {
        User user = null;
        if (userId != null) {
            if (StringUtils.isNotBlank(deviceType)) {//有设备类型，则根据设备类型匹配会员类型查询
                //个人微信
                if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(deviceType)) {
                    WechatUser wechatUser = wechatUserMapper.selectById(userId, merId);
                    if (wechatUser != null) {
                        user = new User();
                        BeanUtils.copyProperties(wechatUser, user);
                        return user;
                    }
                } else if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(deviceType)) { //企业微信号
                    WxworkUser wxworkUser = wxworkUserMapper.selectById(userId, merId);
                    if (wxworkUser != null) {
                        user = new User();
                        BeanUtils.copyProperties(wxworkUser, user);
                        return user;
                    }
                } else if (DeviceTypeEnum.WX_PUB.getKey().equals(deviceType)) { //公众号
                    WxpubUser wxpubUser = wxpubUserMapper.selectById(userId, merId);
                    if (wxpubUser != null) {
                        user = new User();
                        BeanUtils.copyProperties(wxpubUser, user);
                        return user;
                    }
                } else if (DeviceTypeEnum.APP.getKey().equals(deviceType)) { //APP会员
                    AppUser appUser = appUserMapper.selectById(userId, merId);
                    if (appUser != null) {
                        user = new User();
                        BeanUtils.copyProperties(appUser, user);
                        return user;
                    }
                }
            } else {//如果没有设备类型，则依次去各种会员类型表中查询，查询到就返回
                //1-先查询个人微信会员
                WechatUser wechatUser = wechatUserMapper.selectById(userId, merId);
                if (wechatUser != null) {
                    user = new User();
                    BeanUtils.copyProperties(wechatUser, user);
                    return user;
                }
                //2-查询企业微信会员
                WxworkUser wxworkUser = wxworkUserMapper.selectById(userId, merId);
                if (wxworkUser != null) {
                    user = new User();
                    BeanUtils.copyProperties(wxworkUser, user);
                    return user;
                }
                //3-查询公众号会员
                WxpubUser wxpubUser = wxpubUserMapper.selectById(userId, merId);
                if (wxpubUser != null) {
                    user = new User();
                    BeanUtils.copyProperties(wxpubUser, user);
                    return user;
                }
                //4-APP会员
                AppUser appUser = appUserMapper.selectById(userId, merId);
                if (appUser != null) {
                    user = new User();
                    BeanUtils.copyProperties(appUser, user);
                    return user;
                }
            }
        }
        return user;
    }

    /**
     * 根据微信id查询用户信息
     *
     * @param wxid
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public User findUserInfoByWxid(Long merId, String wxid, String deviceType) {
        User user = null;
        if (merId != null && StringUtils.isNotBlank(wxid)) {
            if (StringUtils.isNotBlank(deviceType)) {//有设备类型，则根据设备类型匹配会员类型查询
                if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(deviceType)) { //个人微信
                    //从微信用户缓存中获取用户id
                    Object userIdObject = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WX_USER_ID.getKey(), merId, wxid));
                    if (userIdObject != null) {
                        Long userId = Long.valueOf(userIdObject.toString());
                        WechatUser wechatUser = wechatUserMapper.selectById(userId, merId);
                        if (wechatUser != null) {
                            user = new User();
                            BeanUtils.copyProperties(wechatUser, user);
                            return user;
                        }
                    }
                } else if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(deviceType)) { //企业微信号
                    //从微信用户缓存中获取用户id
                    Object userIdObject = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WXWORK_USER_ID.getKey(), merId, wxid));
                    if (userIdObject != null) {
                        Long userId = Long.valueOf(userIdObject.toString());
                        WxworkUser wxworkUser = wxworkUserMapper.selectById(userId, merId);
                        if (wxworkUser != null) {
                            user = new User();
                            BeanUtils.copyProperties(wxworkUser, user);
                            return user;
                        }
                    }
                } else if (DeviceTypeEnum.WX_PUB.getKey().equals(deviceType)) { //公众号
                    //从微信用户缓存中获取用户id
                    Object userIdObject = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WXPUB_USER_ID.getKey(), merId, wxid));
                    if (userIdObject != null) {
                        Long userId = Long.valueOf(userIdObject.toString());
                        WxpubUser wxpubUser = wxpubUserMapper.selectById(userId, merId);
                        if (wxpubUser != null) {
                            user = new User();
                            BeanUtils.copyProperties(wxpubUser, user);
                            return user;
                        }
                    }
                } else if (DeviceTypeEnum.APP.getKey().equals(deviceType)) { //App
                    //从微信用户缓存中获取用户id
                    Object userIdObject = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.APP_USER_ID.getKey(), merId, wxid));
                    if (userIdObject != null) {
                        Long userId = Long.valueOf(userIdObject.toString());
                        AppUser appUser = appUserMapper.selectById(userId, merId);
                        if (appUser != null) {
                            user = new User();
                            BeanUtils.copyProperties(appUser, user);
                            return user;
                        }
                    }
                }
            } else {
                //从微信用户缓存中获取用户id
                Object userIdObject_wx = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WX_USER_ID.getKey(), merId, wxid));
                if (userIdObject_wx != null) {
                    Long userId = Long.valueOf(userIdObject_wx.toString());
                    WechatUser wechatUser = wechatUserMapper.selectById(userId, merId);
                    if (wechatUser != null) {
                        user = new User();
                        BeanUtils.copyProperties(wechatUser, user);
                        return user;
                    }
                }

                //从微信用户缓存中获取用户id
                Object userIdObject_wxwork = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WXWORK_USER_ID.getKey(), merId, wxid));
                if (userIdObject_wxwork != null) {
                    Long userId = Long.valueOf(userIdObject_wxwork.toString());
                    WxworkUser wxworkUser = wxworkUserMapper.selectById(userId, merId);
                    if (wxworkUser != null) {
                        user = new User();
                        BeanUtils.copyProperties(wxworkUser, user);
                        return user;
                    }
                }

                //从微信用户缓存中获取用户id
                Object userIdObject_wxpub = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WXPUB_USER_ID.getKey(), merId, wxid));
                if (userIdObject_wxpub != null) {
                    Long userId = Long.valueOf(userIdObject_wxpub.toString());
                    WxpubUser wxpubUser = wxpubUserMapper.selectById(userId, merId);
                    if (wxpubUser != null) {
                        user = new User();
                        BeanUtils.copyProperties(wxpubUser, user);
                        return user;
                    }
                }

                //从微信用户缓存中获取用户id
                Object userIdObject_app = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.APP_USER_ID.getKey(), merId, wxid));
                if (userIdObject_app != null) {
                    Long userId = Long.valueOf(userIdObject_app.toString());
                    AppUser appUser = appUserMapper.selectById(userId, merId);
                    if (appUser != null) {
                        user = new User();
                        BeanUtils.copyProperties(appUser, user);
                        return user;
                    }
                }
            }
        }
        return user;
    }


    /**
     * 根据微信id删除会员
     *
     * @param wxid
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteUserInfoByWxid(Long merId, String wxid, String deviceType) {
        if (merId != null && StringUtils.isNotBlank(wxid)) {
            if (StringUtils.isNotBlank(deviceType)) {//有设备类型，则根据设备类型匹配会员类型查询
                if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(deviceType)) { //个人微信
                    //从微信用户缓存中获取用户id
                    Object userIdObject = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WX_USER_ID.getKey(), merId, wxid));
                    if (userIdObject != null) {
                        Long userId = Long.valueOf(userIdObject.toString());
                        wechatUserService.deleteUserById(userId, merId);
                    }
                } else if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(deviceType)) { //企业微信号
                    //从微信用户缓存中获取用户id
                    Object userIdObject = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WXWORK_USER_ID.getKey(), merId, wxid));
                    if (userIdObject != null) {
                        Long userId = Long.valueOf(userIdObject.toString());
                        wxworkUserService.deleteUserById(userId, merId);
                    }
                } else if (DeviceTypeEnum.WX_PUB.getKey().equals(deviceType)) { //公众号
                    //从微信用户缓存中获取用户id
                    Object userIdObject = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.WXPUB_USER_ID.getKey(), merId, wxid));
                    if (userIdObject != null) {
                        Long userId = Long.valueOf(userIdObject.toString());
                        wxpubUserService.deleteUserById(userId, merId);
                    }
                } else if (DeviceTypeEnum.APP.getKey().equals(deviceType)) { //app
                    //从微信用户缓存中获取用户id
                    Object userIdObject = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.APP_USER_ID.getKey(), merId, wxid));
                    if (userIdObject != null) {
                        Long userId = Long.valueOf(userIdObject.toString());
                        appUserService.deleteUserById(userId, merId);
                    }
                }
            }
        }
    }

    /**
     * 修改用户的账户余额
     *
     * @param user
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public int updateBalance(User user) {
        //个人微信
        if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(user.getDeviceType())) {
            WechatUser wechatUser = new WechatUser();
            BeanUtils.copyProperties(user, wechatUser);
            wechatUser.setMerId(user.getMerId());
            wechatUser.setId(user.getId());
            wechatUser.setVersion(user.getVersion());
            wechatUser.setBalance(user.getBalance());
            wechatUser.setIntegral(user.getIntegral());
            wechatUser.setUpdateTime(user.getUpdateTime());
            wechatUser.setDeviceType(user.getDeviceType());
            return wechatUserMapper.updateBalance(wechatUser);
        } else if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(user.getDeviceType())) { //企业微信号
            WxworkUser wxworkUser = new WxworkUser();
            BeanUtils.copyProperties(user, wxworkUser);
            wxworkUser.setMerId(user.getMerId());
            wxworkUser.setId(user.getId());
            wxworkUser.setVersion(user.getVersion());
            wxworkUser.setBalance(user.getBalance());
            wxworkUser.setIntegral(user.getIntegral());
            wxworkUser.setUpdateTime(user.getUpdateTime());
            wxworkUser.setDeviceType(user.getDeviceType());
            return wxworkUserMapper.updateBalance(wxworkUser);
        } else if (DeviceTypeEnum.WX_PUB.getKey().equals(user.getDeviceType())) { //公众号
            WxpubUser wxpubUser = new WxpubUser();
            BeanUtils.copyProperties(user, wxpubUser);
            wxpubUser.setMerId(user.getMerId());
            wxpubUser.setId(user.getId());
            wxpubUser.setVersion(user.getVersion());
            wxpubUser.setBalance(user.getBalance());
            wxpubUser.setIntegral(user.getIntegral());
            wxpubUser.setUpdateTime(user.getUpdateTime());
            wxpubUser.setDeviceType(user.getDeviceType());
            return wxpubUserMapper.updateBalance(wxpubUser);
        } else if (DeviceTypeEnum.APP.getKey().equals(user.getDeviceType())) { //APP
            AppUser appUser = new AppUser();
            BeanUtils.copyProperties(user, appUser);
            appUser.setMerId(user.getMerId());
            appUser.setId(user.getId());
            appUser.setVersion(user.getVersion());
            appUser.setBalance(user.getBalance());
            appUser.setIntegral(user.getIntegral());
            appUser.setUpdateTime(user.getUpdateTime());
            appUser.setDeviceType(user.getDeviceType());
            return appUserMapper.updateBalance(appUser);
        }
        return 0;
    }
}
